package crew.gwt.client.widgets.util;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.ToggleButton;

public class RadioAsFloatButton extends Composite implements HasValue<Float> {

	private boolean valueChangeHandlerInitialized;
	
	private final ToggleButton wrappedButton;
	
	public RadioAsFloatButton(String label) {
		wrappedButton = new ToggleButton(label);
		wrappedButton.addValueChangeHandler(valueChangeHandler);
		initWidget(wrappedButton);
	}

	/**
	 * The handler added to the widget to fire the value changing.
	 */
	private final ValueChangeHandler<Boolean> valueChangeHandler = new ValueChangeHandler<Boolean>() {
		@Override
		public void onValueChange(ValueChangeEvent<Boolean> event) {
			try{
				// Fire the event with the float value corresponding of the boolean.
				float value = event.getValue() ? 1f : 0f;
				ValueChangeEvent.fire(RadioAsFloatButton.this, value);
			}catch(NumberFormatException ex){
				addStyleName("Form-Element-Wrong");
			}
		}
	};
	
	@Override
	public HandlerRegistration addValueChangeHandler(ValueChangeHandler<Float> handler) {
		// Initialization code
	    if (!valueChangeHandlerInitialized) {
	      valueChangeHandlerInitialized = true;
	      addChangeHandler(new ChangeHandler() {
	        public void onChange(ChangeEvent event) {
	          ValueChangeEvent.fire(RadioAsFloatButton.this, getValue());
	        }
	      });
	    }
	    return addHandler(handler, ValueChangeEvent.getType());
	}
	public HandlerRegistration addChangeHandler(ChangeHandler handler) {
		return addDomHandler(handler, ChangeEvent.getType());
	}

	@Override
	public Float getValue() {
		return wrappedButton.getValue() ? 1f : 0f;
	}

	@Override
	public void setValue(Float value) {
		setValue(value, false);
	}

	@Override
	public void setValue(Float value, boolean fireEvents) {
		Float oldValue = getValue();
		wrappedButton.setValue( value > 0 ? true : false );
	    if (fireEvents) {
	      ValueChangeEvent.fireIfNotEqual(this, oldValue, value);
	    }
	}
	
	public boolean isActivated() {
		return wrappedButton.getValue();
	}
}
